package com.gary.consumer;

import com.gary.entity.MyInvocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *  消费者 连接
 * @author pengrui3
 * @date 2020/12/11-23:16
 */
public class HttpClient {

    public static String post(String hostName, Integer port, MyInvocation myInvocation) {
        URL url = null;
        OutputStream outputStream = null;
        ObjectOutputStream oos = null;
        InputStream in = null;
        try {
            //建立连接
            url = new URL("http", hostName, 8080, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            //发送调用信息
            outputStream = httpURLConnection.getOutputStream();
            oos = new ObjectOutputStream(outputStream);
            oos.writeObject(myInvocation);

            //将输入流转为字符串
            in = httpURLConnection.getInputStream();
            return IOUtils.toString(in);
        } catch (IOException e) {
                e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (in != null) {
                    in.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
